﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace StockMonitor.Business
{
    /// <summary>
    /// 搜狐历史价格获取接口，最多获取最近86天数据
    /// </summary>
    public class SohuHistoryPriceProvider : IHistoryPriceProvider
    {
        private static readonly string UrlFormat = "http://q.stock.sohu.com/app2/history.up?method=history&code=cn_{0}&sd={1}&ed={2}&t=d&res=js";

        /// <summary>
        /// 获取某只股票历史价格
        /// </summary>
        /// <param name="stockCode">股票代码</param>
        /// <param name="dayCount">获取从昨天起的天数</param>
        /// <returns>
        /// 历史价格列表
        /// </returns>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 4:54 PM</datetime>
        /// </remarks>
        public List<StockPrice> GetHistoryPrice(string stockCode, int dayCount)
        {
            List<StockPrice> results = new List<StockPrice>();

            DateTime startDate = DateTime.Today.AddDays(-1 * dayCount);

            string url = string.Format(UrlFormat, stockCode, startDate.ToString("yyyy-MM-dd"), DateTime.Today.ToString("yyyy-MM-dd"));

            using (WebClient wc = new WebClient())
            {
                Stream resStream = wc.OpenRead(url);
                using (StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default))
                {
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();
                        if (line.StartsWith("['") && (line.EndsWith("],") || line.EndsWith("]")))
                        {
                            results.Add(
                                new StockPrice()
                            {
                                StockCode = stockCode,
                                Price = double.Parse(line.Replace('\'', ' ').Split(',')[2]),
                                Date = Convert.ToDateTime(line.Substring(2, 10))
                            });
                        }
                    }
                }
            }

            results.Reverse();

            return results;
        }

        /// <summary>
        /// 获取某只股票历史收盘价格
        /// </summary>
        /// <param name="stockCode">股票代码</param>
        /// <param name="dayCount">获取从昨天起的天数</param>
        /// <returns>
        /// 历史收盘价格从远到进排序
        /// </returns>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 4:54 PM</datetime>
        /// </remarks>
        public List<double> GetHistoryClosePrice(string stockCode, int dayCount)
        {
            List<double> results = new List<double>();

            DateTime startDate = DateTime.Today.AddDays(-1 * dayCount);

            string url = string.Format(UrlFormat, stockCode, startDate.ToString("yyyy-MM-dd"), DateTime.Today.ToString("yyyy-MM-dd"));

            using (WebClient wc = new WebClient())
            {
                Stream resStream = wc.OpenRead(url);
                using (StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default))
                {
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();
                        if (line.StartsWith("['") && (line.EndsWith("],") || line.EndsWith("]")))
                        {
                            results.Add(double.Parse(line.Replace('\'', ' ').Split(',')[2]));
                        }
                    }
                }
            }

            results.Reverse();

            return results;
        }
    }
}
